import time
import json
import random
import paho.mqtt.client as mqtt
import base64
import matplotlib.pyplot as plt
import soundfile as sf
import librosa

#username和password
#可直接在设备页面一键复制
client_id = f"picture|securemode=2,signmethod=hmacsha1,timestamp=1719976922248|"
timestamp = str(int(time.time()))
username = f"picture&k17qfYOFMoU"
password = f"AF550D71D6D827463B6C1E9C06A52BA1C2715477"

# MQTT连接地址
broker = f"k17qfYOFMoU.iot-as-mqtt.cn-shanghai.aliyuncs.com"
port = 1883

# 回调函数
def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe(f"/sys/k17qfYOFMoU/picture/thing/event/property/post")
    #注意把自己的设备信息更换
def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload))

# 创建客户端
client = mqtt.Client(client_id=client_id)
client.username_pw_set(username, password)
# 绑定回调函数
client.on_connect = on_connect
client.on_message = on_message
# 连接到阿里云物联网平台
client.connect(broker, port, 60)
# 启动MQTT客户端
client.loop_start()

# topic = f"/sys/k17qfYOFMoU/picture/thing/event/property/post"
# while True:
#     random_number = random.randint(1000000000, 9999999999)
#     payload = {
#         "method": "thing.event.property.post",
#         "params": {
#             "image": str(random_number)
#         }
#     }
#     client.publish(topic, json.dumps(payload))
#     print(f"Published: {json.dumps(payload)}")
#     time.sleep(3)

topic = f"/k17qfYOFMoU/picture/user/update"
image = "./hs_img.jpg"
def plot_signal(audio_data, title=None):
    plt.figure(figsize=(6, 3), dpi=200)
    plt.plot(audio_data, linewidth=1)
    plt.grid()
    plt.savefig('./hs_img.jpg')

def get_image_base64_block(image_path="./hs_img.jpg", block_size=102400):
    with open(image_path, "rb") as image_file:  # 二进制
        image_data = base64.b64encode(image_file.read()).decode('utf-8')
    for i in range(0, len(image_data), block_size):
        yield image_data[i:i + block_size]

def publish_image_block(image_block, block_index):

    payload = {
        "method": "thing.event.property.post",
        "params": {
            "image": image_block,
            "block_index": block_index
        }
    }
    result = client.publish(topic, json.dumps(payload))
    print(f"Publishing block {block_index}: {json.dumps(payload)} with result: {result}")

index = 1
rate = 0
file = "../test.wav"
audio_data, fs = sf.read(file)
plot_signal(audio_data,title=file)
# audio_data, sr = librosa.load(file, sr=2000)
for i in range(len(audio_data)):
    if audio_data[i] > 0.4:
        rate = rate + 1
print(rate)
# while True:
for image_block in get_image_base64_block():
    publish_image_block(image_block,index)
    index = index + 1
    time.sleep(1)  # 可以根据需要调整发送间隔时间
    print(len(image_block),image_block)
# time.sleep(1)  # 每秒发送一张图片
print("xing")
# for image_block in get_image_base64_block(image):
#     publish_image_block(image_block,index)
#     index = index + 1
#     time.sleep(1)  # 可以根据需要调整发送间隔时间
# time.sleep(2)  # 每秒发送一张图片